// JavaScript Document

var gallery = {
	
    ajax_page: null,
    total_images_per_page: 15,
    $tabs: null,
	old_tag: null,
	last_tag: null,
	
    init: function() {
		
        gallery.ajax_page = 'ajax_pages/galleries.php';
		
        $p.addEvent("#gallery_form", 'submit', function() {
            var validated = gallery.validateGalleryForm(this);
			
            if( validated ) {
                var action = $p("#gallery_form #action").val();
				
                if( action == 'add_gal' ) {
                    $p.postForm( gallery.ajax_page, null, this, function(data) {

						try {
							var obj = $p.parseJSON(data);
							$p("#gallery_form #id").val(obj.id);
							$p("#image-uploader-form #GalleryID").val(obj.id);
							$p("#image-uploader-form #destFolder").val(obj.GalleryFolder + "pics/");
							$p("#image-uploader-form #thumbFolder").val(obj.GalleryFolder + "thumbs/");
							
						} catch(e) {
							alert("Saved Gallery, but returned data not in valid JSON format\n\n" + data);
						}
						
                        document.getElementById("images-tab").style.visibility = 'visible';
                        $p("#gallery_form #action").val('edit_gal');
                        $p("#gallery_form #Submit").val("Save Gallery");
						
                        gallery.$tabs.tabs('select', 1);
                    });
                } else {
					
                    // if not adding a gallery, simply submit the form
                    this.submit();
                }
            }
        });
		
		// cache the current gallery tag if present
		if( document.getElementById("GalleryTag") ) {
			gallery.old_tag = document.getElementById("GalleryTag").value;
		}
		
		// register an onblur event for the GalleryTag field to help determine
		$p.addEvent('#GalleryTag','blur',function() {
			if( this.value == '' || this.value == gallery.old_tag || gallery.last_tag == this.value ) {
				return;	
			}
			
			// cache the current tag value for later to prevent checking again, if the user
			// has not entered a new value to check with
			gallery.last_tag = this.value;
			
			// build the ajax query
            var query = "action=check-tag&tag=" + this.value;
			
            $p.post( gallery.ajax_page, query, function(data) {
				var ti = document.getElementById("tag_info");
                if( data == 'false' ) {
                    ti.innerHTML = "Gallery Tag Currently Used";
					ti.className = "small invalid";
                } else {
                    ti.innerHTML = "Gallery Tag Valid";
					ti.className = "small valid";
                }
            });
        });
		
        $p.addEvent('#Cancel', 'click',function() {
            history.back();
        });
		
        $p.addEvent("#checker",'click',function() {
            var checked = this.checked;
            $p.all(".cms-data-table td input[type=checkbox]", function(el) {
                el.checked = checked;
            });
        });
		
        $p.addEvent("#image-checker",'click',function() {
            var checked = this.checked;
            $p.all("#image-content input[type=checkbox]", function(el) {
                el.checked = checked;
				
                if( checked ) {
                    document.getElementById("img-item-" + el.value).className = "selected";
                } else {
                    document.getElementById("img-item-" + el.value).className = "";
                }
            });
        });
		
		
        $p.addEvent("#GalleryTag",'keyup',function() {
            document.getElementById("GalleryFolder").value = "../assets/images/gallery/" + this.value + "/";
        });
		
        // initiate the tabs
        gallery.$tabs = $("#gallery-tabs").tabs({
            fx : {
                opacity:'toggle'
            }
        });
		
        // register the delete selected link for the galleries
        $p.addEvent("#delete-selected-link",'click',function() {
            gallery.deleteSelectedGalleries();
        });

        $p.addEvent("#image-add-photo",'click',function() {
            gallery.showPhotoUploader();
        });

        // register the delete selected link for the images
        $p.addEvent("#image-delete-selected",'click', function() {
            gallery.deleteSelectedImages();
        });

        // register the delete link for the various galleries
        $p.all(".cms-data-table .delete-link", function(el, i) {

            $p.addEvent(el, 'click', function() {
                var gallery_name = this.getAttribute('data-galname');
                var gallery_id = this.getAttribute('data-id');

                $p.showConfirmMessage({
                    title: 'Confirm Gallery Delete',
                    content: "Delete <b>" + gallery_name + "</b> and associated images?",
                    okButtonText: 'Delete Gallery',
                    okButtonAction: function() {
                        var query = "action=delete-gal&gal-ids=" + gallery_id;

                        $p.setLoaderMessage("Deleting Gallery. Please Wait...");
                        $p.post('ajax_pages/galleries.php', query, 'pm-pane-content', function(data) {
                            $p.remove('#gal-row-' + gallery_id);
                            $p.hideDialog();
                        });

                        // prevent dialog from closing
                        return false;
                    }
                });
            });
        });

        gallery.setupImageLinks();

        $p("#images-footer .pager-link").bind('click', function() {
			var page = this.getAttribute('data-page');
			var total = gallery.total_images_per_page;
			var gallery_id = this.getAttribute("data-gallery-id");
			var el = this;

			var query = "action=show-images&gallery_id=" + gallery_id + "&page=" + page + "&total=" + total;
			$p.post( gallery.ajax_page, query, function(data) {
				$p('#image-content').html(data);
				
				gallery.setupImageLinks();

				$p.all("#images-footer .pager-link", function(link_el) {
					if( link_el == el ) {
						link_el.className = "pager-link selected";
					} else {
						link_el.className = "pager-link";
					}
				});
			});
        });

        // register all the publish or unpublish-links
        $p(".cms-data-table .cms-publish-link, .cms-data-table .cms-unpublish-link").bind('click', function(e) {

			if( this.className == 'cms-publish-link' ) {
				gallery.publishGallery('unpublish', this );
			} else {
				gallery.publishGallery('publish', this );
			}
        });
    },

    publishGallery: function(action, linkEl) {
        var query = "action=" + action + "&id="	+ linkEl.id;

        $p.post( gallery.ajax_page, query, function(data) {

            if( action == "publish" ) {
                linkEl.className = 'cms-publish-link';
                linkEl.title = 'Published (Click To Unpublish)';
                linkEl.onclick = function() {
                    gallery.publishGallery('unpublish', this);
                }
            } else {
                linkEl.className = 'cms-unpublish-link';
                linkEl.title = 'Unpublished (Click To Publish Now)';
                linkEl.onclick = function() {
                    gallery.publishGallery('publish', this);
                }
            }
        });
    },

    validateGalleryForm: function(form) {

        return $p(form).validate({
            'GalleryName' : 'Gallery Name',
            'GalleryFolder' : 'Gallery Folder',
            'GalleryTag' : 'Gallery Alias/Tag Name',
            'ImageWidth' : 'Max Width Of Gallery Images',
            'ThumbnailWidth' : 'Max Width Of Thumbnail Images'
        });
    },

    setupImageLinks: function() {
        $p("#image-content .delete-link").bind('click', function() {
            gallery.deleteImage( this );
        });

        $p("#image-content .edit-link").bind('click', function() {
            gallery.showImageEditorForm( this );
        });
		
		$p("#image-content .image_box img").bind('click', function(el) {
			var img = new Image();
				img.src = $p(this).attr("data-url");
				img.onload = function() {
					$p("#pm-pane-content").html("<div><img src='" + this.src + "' alt='' /></div>");
				};
			 
			$p.showMessage({
				title: 'Image',
				content: 'Loading Image For Preview. Please Wait...',
				okButtonText: 'Close'
			});
		});
		
		$p("#image-content input[type=checkbox]").bind('click', function() {
			if( this.checked ) {
				document.getElementById("img-item-" + this.value).className = "selected";
			} else {
				document.getElementById("img-item-" + this.value).className = "";
			}
        });
    },

    showPhotoUploader: function() {
        $p.showDialog({
            title: 'Upload New Image',
            content: $p("#image-uploader-form").html(),
            okButtonText: 'Upload Image',
            showOverlay: true,
            width: '620px',
            //top: '100px',

            okButtonAction: function() {
				
				var checked = $p("#pm-pane-content form").validate({
					'ImageName':'Provide A Name For Your Image',
					'ImageDescription': 'Provide A Description For The Image',
					'uploadFile':'No File Has Been Specified For Upload'
				});
				
                if( !checked ) {
                    return false;
                }

                var query = "action=upload-image&" + $p("#pm-pane-content form").serialize();

				$p.setLoaderMessage("Uploading Image To Gallery. Please Wait...");
                $p.postMultiPartForm( gallery.ajax_page, $p("#pm-pane-content form").node(), 'pm-pane-content', function(data) {

                    // if the browser supports native JSON parsing then try to parse the returned
                    // data
                    if( JSON ) {
                        try {
                            var obj = $p.parseJSON(data);

                            var img = document.createElement("img");
                            img.src = obj.ImageThumbURL;
                            img.alt = obj.ImageDescription;

                            var img_box = document.createElement("div");
                            img_box.className = 'image_box';
                            img_box.appendChild(img);

                            var name_box = document.createElement("div");
                            name_box.className = "name_box";
                            name_box.appendChild( document.createTextNode(obj.ImageName) );

                            var input = document.createElement("input");
                            input.type = "checkbox";
                            input.value = obj.id;

                            var edit_link = document.createElement("a");
                            edit_link.href = "#";
                            edit_link.setAttribute("data-id", obj.id);
                            edit_link.setAttribute("data-name", obj.ImageName);
                            edit_link.innerHTML = '<img src="images/icons/image_edit.png" alt="edit" width="16" height="16" border="0" align="absmiddle" /> Edit';
                            edit_link.onclick = function() {
                                gallery.showImageEditorForm( this );
                            };

                            var delete_link = document.createElement("a");
                            delete_link.href = "#";
                            delete_link.setAttribute("data-id", obj.id);
                            delete_link.setAttribute("data-name", obj.ImageName);
                            delete_link.innerHTML = '<img src="images/icons/image_delete.png" alt="del" width="16" height="16" border="0" align="absmiddle" /> Delete';
                            delete_link.onclick = function() {
                                gallery.deleteImage(this);
                            };


                            var link_box = document.createElement("div");
                            link_box.appendChild(input);
                            link_box.appendChild(edit_link);
                            link_box.appendChild(delete_link);

                            var option_box = document.createElement("div");
                            option_box.className = "options_box";
                            option_box.appendChild( name_box );
                            option_box.appendChild( link_box );

                            var li = document.createElement("li");
                            li.id = "img-item-" + obj.id;
                            li.appendChild(img_box);
                            li.appendChild(option_box);

                            var ul = $p.$("#image-content ul");

                            // if the image content list contains the NO DATA instruction,
                            // remove it before adding the new list items
                            if( $p.all("#image-content ul li").length == 0 ) {
                                $p.removeAll("#image-content ul div");
                            }

                            ul.insertBefore(li, ul.firstChild );

                        } catch(e) {
                            alert("Returned Data is not in valid JSON format\n" + data);

                        }

                    // simply refresh the page to load the new data
                    } else {

                    }

                    $p.hideDialog();
                });

                // prevent dialog from closing
                return false;
            }
        });

        // attach a handler to the uploadFile field if it exists
        $p('#pm-pane-content #uploadFile').bind('change', function(evt) {
			
			if( evt.target && evt.target.files ) {
				var size = evt.target.files[0].size; 
				var type = evt.target.files[0].type; 
				var max_size = $p("#maxlimit").val();
	 
				if (size > max_size) {
					alert("The File You Are Trying To Upload Is Greater Than The Max Limit of " + max_size + " Bytes Permitted. "
						+ "Please Resize Image Before Attempting Upload.");
				  
					$p(this).val("");
					return false;
				}
			}

            var dstFolder = $p("#pm-pane-content #destFolder").val();
            var thumbFolder = $p("#pm-pane-content #thumbFolder").val();
            var file_path = $p("#pm-pane-content #uploadFile").val();

            // calculate the data time to be used as the destination file name
            var now = new Date();
            var dateStr = now.getFullYear() + "" + (now.getMonth() + 1) + "" + now.getDate() + "_" + now.getHours() + "" + now.getMinutes() + "" + now.getSeconds();
            $p('#pm-pane-content #destFileName').val( "img" + dateStr );

            // generate the destination file name to used for the picture field
            file_utils.generateDestinationFileName('#pm-pane-content #ImageFile', dstFolder, file_path, 'img');
            file_utils.generateDestinationFileName('#pm-pane-content #ThumbPath', thumbFolder, file_path, 'img');

        });
    },

    showImageEditorForm: function(link_el) {

        if( link_el == null ) {
            return;
        }

        var image_id = link_el.getAttribute("data-id");
        var image_name = link_el.getAttribute("data-name");

        $p.showDialog({
            title: 'Edit Information For <b>' + image_name + '</b>',
            content: '',
            okButtonText: 'Save Changes',
            width: '600px',
            okButtonAction: function() {
                var new_image_name = $p("#pm-pane-content #ImageName").val();
                var query = "action=save-image-data&" + $p("#pm-pane-content form").serialize();

                $p.post( gallery.ajax_page, query, function(data) {
					$p('#pm-pane-content').html(data);
                    $p("#img-item-" + image_id + " .name").html( new_image_name );
                });
            }
        });

        var query = "action=load-image-data&id=" + image_id;
        $p.post( gallery.ajax_page, query, function(data) {
			//$p('#pm-pane-content').html(data);
            $p("#pm-pane-content").html( document.getElementById("image-data-editor").innerHTML );

            if( JSON ) {
                var obj = $p.parseJSON(data);
                $p("#pm-pane-content #id").val( obj.id );
                $p("#pm-pane-content #ImageName").val( obj.ImageName );
                $p("#pm-pane-content #ImageDescription").val( obj.ImageDescription );
                $p("#pm-pane-content #GalleryImage").attr("src", obj.ImageThumbURL);
            }
        });
    },

    deleteImage: function(link_el) {
        var image_id = link_el.getAttribute("data-id");
        var image_name = link_el.getAttribute("data-name");

        $p.showConfirmMessage({
            title: 'Confirm Image Delete',
            content: "Do You Want To Delete <b>" + image_name + "</b> From Gallery?",
            okButtonText: 'Delete Image',
            okButtonAction: function() {
                var query = "action=delete-images&img-ids=" + image_id;

                $p.setLoaderMessage("Deleting Image From Gallery. Please Wait...");
                $p.post('ajax_pages/galleries.php', query, 'pm-pane-content', function(data) {
                    $p('#img-item-' + image_id).remove();
                    $p.hideDialog();
                });

                // prevent dialog from closing
                return false;
            }
        });
    },

    deleteSelectedGalleries: function() {
        var els = $p.all(".cms-data-table td input[type=checkbox]");

        // we'll manually check for selected elements since IE can't handle the
        // :checked selector to return only those elements
        var selected = [];
        for( i = 0, j = 0; i < els.length; i++ ) {
            if( els[i].checked ) {
                selected[j++] = els[i].value;
            }
        }

        if( selected.length == 0 ) {
            alert("Please Select Galleries To Delete");
            return;
        }

        $p.showConfirmMessage({

            title: 'Confirm Gallery Delete',
            content: "Delete Selected Gallery(ies) and associated images?",
            okButtonText: 'Delete Gallery',
            okButtonAction: function() {

                var query = "action=delete-gal&gal-ids=" + selected;

                $p.setLoaderMessage("Deleting Selected Galleries. Please Wait...");
                $p.post('ajax_pages/galleries.php', query, 'pm-pane-content', function(data) {

                    $p.all(".cms-data-table td input[type=checkbox]", function(el) {
                        if( el.checked ) {
                            $p.remove('#gal-row-' + el.value);
                        }
                    });

                    // close dialog when done
                    $p.hideDialog();
                });

                // prevent dialog from closing
                return false;
            }
        });
    },

    deleteSelectedImages: function() {
        var els = $p.all("#image-content input[type=checkbox]");

        // we'll manually check for selected elements since IE can't handle the
        // :checked selector to return only those elements
        var selected = [];
        for( i = 0, j = 0; i < els.length; i++ ) {
            if( els[i].checked ) {
                selected[j++] = els[i].value;
            }
        }

        if( selected.length == 0 ) {
            alert("Please Select Images To Delete From This Gallery");
            return;
        }

        $p.showConfirmMessage({

            title: 'Confirm Image Delete',
            content: "<center>Delete Selected Image(s) From This Gallery?</center>",
            okButtonText: 'Delete Image',
            okButtonAction: function() {

                var query = "action=delete-images&img-ids=" + selected;

                $p.setLoaderMessage("Deleting Selected Images From Gallery. Please Wait...");
                $p.post('ajax_pages/galleries.php', query, 'pm-pane-content', function(data) {

                    $p.all("#image-content input[type=checkbox]", function(el) {
                        if( el.checked ) {
                            $p.remove('#img-item-' + el.value);
                        }
                    });

                    // close dialog when done
                    $p.hideDialog();
                });

                // prevent dialog from closing
                return false;
            }
        });
    }
};